package com.mgg.message.consumer;

import java.util.Map;

import com.mgg.common.consumer.MessageConsumer;
import com.mgg.common.messaging.SmsSendProcessor;
import com.mgg.common.payload.SmsSendPayload;
import com.mgg.common.util.JsonUtils;
import com.mgg.message.service.sms.SmsService;
import com.mgg.message.sms.SmsSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.stereotype.Component;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;

@Component
public class SmsSendMessageConsumer implements MessageConsumer<SmsSendPayload> {

	Logger log = LoggerFactory.getLogger(getClass());
	
	@Autowired
    private SmsService smsService;
	
	@Autowired
    private SmsSender smsSender;
	
    @StreamListener(SmsSendProcessor.INPUT)
	@Override
	public void receiveMessage(SmsSendPayload payload) {
    	log.info("【短信发送】，payload = {}", JsonUtils.toJson(payload));
    	Integer smsType = payload.getSmsType();
    	Integer subType = payload.getSubType();
    	String mobile = payload.getMobile();
    	String param = payload.getParam();
    	
    	try {
			Map<String,String> configMap = smsService.getSmsConfigByType(smsType,subType);
			
			String signName = configMap.get("sign_name");
			String templateCode = configMap.get("template_code");
			
			SendSmsResponse sendSmsResponse = smsSender.send(mobile, signName, templateCode, param);
			
			String smsId = configMap.get("id");
			String content = configMap.get("content");
			
			System.out.println(sendSmsResponse.toString());
			if (sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
				// 请求成功
				smsService.insertSmsSendLog(smsId,mobile,param,"","100");
			} else {
				// 请求失败
				String remark = "code: " + sendSmsResponse.getCode() + ", message: " + sendSmsResponse.getMessage();
				smsService.insertSmsSendLog(smsId,mobile,param,remark,"99");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
